<script setup lang="ts">
defineOptions({
  name: "alarmDetail"
});
import { ref, onMounted, toRefs, reactive, getCurrentInstance } from "vue";
import { PxMessage } from "px-ui";
import { queryDictData } from "@/api/common";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import lineChart from "../lineChart/index.vue";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { getFabZone, queryChildByTypeCodeAndItemValue, queryAreaWornings } from "@/api/machineClass";

const { proxy }: any = getCurrentInstance();

const loading = ref(false);
const searchIdAlarm = ref<any>("");
const lineBegin = ref("");
const lineWidth = ref<any>(10);
const tableRef = ref(null);
const searchId = ref("");

const filterList = ref([]);
const testCompanyList = ref([
  {
    value: 4,
    label: "近4小时"
  },
  {
    value: 8,
    label: "近8小时"
  },
  {
    value: 16,
    label: "近16小时"
  }
]);

const minitesList = ref([
  {
    value: 10,
    label: "10分钟"
  },
  {
    value: 20,
    label: "20分钟"
  },
  {
    value: 30,
    label: "30分钟"
  }
]);

const router = useRouter();
const route = useRoute();

const state = reactive<any>({
  tableAlarmData: [],
  tableAlarmSelectedData: [],
  tableAlarmDataAll: [],
  alarmOptions: {},
  areaData: [],
  dateArr: [],
  dateRangeAlarm: [],
  selectIds: [],
  queryAlarmParams: {}
});

const { alarmOptions, queryAlarmParams, areaData, dateArr, selectIds, dateRangeAlarm, tableAlarmData, tableAlarmDataAll, tableAlarmSelectedData } =
  toRefs(state);

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let hour = date.getHours() < 10 ? "0" + date.getHours().toString() : date.getHours().toString();
  let minites = date.getMinutes() < 10 ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
  let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${year}-${month}-${da}`, `${year}-${month}-${da}`]; // 近一年时间范围
  // return [`${year}-${month}-${lastda} 00:00:00`, `${year}-${month}-${da} ${hour}:${minites}:${seconds}`]; // 近一年时间范围
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

// 合并同类项数组
const mergeDataByProperty = arr => {
  const merged = [];
  let propertyValues = {};
  const keyArr: any = Array.from(new Set(arr.map(item => item.point))) || [];
  for (const val in keyArr) {
    propertyValues[keyArr[val]] = [];
    console.log(val);
    arr.forEach(item => {
      if (item.point === keyArr[val]) {
        propertyValues[keyArr[val]].push({
          name: item.alarmTime,
          value: Number(item.realityValue)
        });
      }
    });
  }
  return propertyValues;
};

// 获取秒的X轴间隔
const getAllSecondsData = (startTime, endTime) => {
  let currentTime = new Date(startTime);
  let endT = new Date(endTime);
  let secondsData = [];
  while (currentTime <= endT) {
    // 构建当前秒的数据，这里以对象的形式返回秒数和时间戳
    let hour = currentTime.getHours() < 10 ? "0" + currentTime.getHours().toString() : currentTime.getHours().toString();
    let minites = currentTime.getMinutes() < 10 ? "0" + currentTime.getMinutes().toString() : currentTime.getMinutes().toString();
    let seconds = currentTime.getSeconds() < 10 ? "0" + currentTime.getSeconds().toString() : currentTime.getSeconds().toString();
    let data = {
      value: hour + ":" + minites + ":" + seconds,
      timestamp: currentTime.getTime()
    };
    secondsData.push(data);
    // 将当前时间向前推进一秒
    currentTime.setSeconds(currentTime.getSeconds() + 1);
  }

  return secondsData;
};

// 日期转化
const initDate = (val: number) => {
  const now = new Date();
  const utcTime = now.toISOString();
  const beijingTime = new Date(utcTime).getTime() + 8 * 60 * 60 * 1000;
  const start = beijingTime - val * 60 * 60 * 1000;
  const startTime = new Date(start).toISOString().slice(0, 19).replace("T", " ");
  const endTime = new Date(beijingTime).toISOString().slice(0, 19).replace("T", " ");
  return [startTime, endTime];
};

const handleChangeLine = (val: number) => {
  if (!lineBegin.value) {
    PxMessage({
      message: "请选择开始时间",
      type: "warning"
    });
    lineWidth.value = null;
    return;
  }
  console.log(new Date(lineBegin.value), "66666666666");
  if (val) {
    dateArr.value = initLineDate(val);
    console.log(lineBegin.value, dateArr.value, "66666666666");
  }
};

// 日期转化
const initLineDate = (val: number) => {
  const start = proxy.parseTime(new Date(lineBegin.value).getTime(), "{y}-{m}-{d} {h}:{i}:{s}");
  const end = proxy.parseTime(new Date(lineBegin.value).getTime() + val * 60 * 1000 - 1, "{y}-{m}-{d} {h}:{i}:{s}");
  return [start, end];
};

const turnBack = () => {
  router.go(-1);
};

// 查询所有报警
const queryAllAlarm = async val => {
  const params = { ...queryAlarmParams.value };
  searchIdAlarm.value = route.query.area || "";
  params.pageNum = 1;
  params.pageSize = 9999; // 默认查询所有数据
  params[`${searchIdAlarm.value.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] =
    searchIdAlarm.value.indexOf("ROOM") === -1 ? [searchIdAlarm.value] : searchIdAlarm.value;
  if (val) {
    dateArr.value = initLineDate(lineWidth.value);
    const param1 = proxy.addDateRange(params, dateArr.value, "startTime", "endTime");
    // const param1 = proxy.addDateRange(params, ["", ""], "startTime", "endTime");
    const res: any = await queryAreaWornings(param1);
    // 初始化曲线--根据已选点位数据更新出曲线宽度对应的数据
    const chartsData = res.data.filter(item => selectIds.value.indexOf(item.id) !== -1);
    console.log("chartsData", chartsData);
    initLineChart(chartsData || []);
    // initLineChart(res.data || []);
  } else {
    const param2 = proxy.addDateRange(params, dateRangeAlarm.value, "startTime", "endTime");
    const data: any = await queryAreaWornings(param2);
    tableAlarmData.value = data?.data.slice(queryAlarmParams.value.pageNum - 1, queryAlarmParams.value.pageSize);
    tableAlarmDataAll.value = data?.data || [];
    tableAlarmSelectedData.value = [];
    clearTableSelection();
  }
};

// 重置Alarm列表
const resetAlarmTable = () => {
  dateRangeAlarm.value = [];
  searchIdAlarm.value = route.query.area || "";
  queryAlarmParams.value = {
    pageNum: 1,
    pageSize: 10
  };
  queryAllAlarm(null);
};

// 重置Alarm列表
const resetAlarm = () => {
  lineBegin.value = proxy.parseTime(new Date(lineBegin.value).getTime() - 10 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}"); // 默认10分钟
  lineWidth.value = 10;
  // dateArr.value = [];
  dateArr.value = initLineDate(lineWidth.value);
  queryAllAlarm("flag");
};

const queryAlarmTable = (val: any) => {
  console.log(val);
  queryAlarmParams.value.pageNum = val.page;
  queryAlarmParams.value.pageSize = val.limit;
  const startIndex = (val.page - 1) * val.limit;
  const endIndex = startIndex + val.limit;
  tableAlarmData.value = tableAlarmDataAll.value.slice(startIndex, endIndex);
};

const clearTableSelection = () => {
  if (tableRef.value) {
    tableRef.value.clearSelection();
  }
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  const ids = selection.map(item => item.id);
  tableAlarmSelectedData.value = selection;
  selectIds.value = ids;
};

const handleAreaChange = (val: any) => {
  // queryParams.value[`${val.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] = val;
};

const handleChangeAlarm = (val: number) => {
  if (val) {
    dateRangeAlarm.value = initDate(val);
  }
};

// 刷新曲线
const initLineChart = chartData => {
  console.log("chartData", chartData);
  let legendData = Array.from(new Set(chartData.map(item => item.point)));
  let mergeData = mergeDataByProperty(chartData);
  let featData = getAllSecondsData(dateArr.value[0], dateArr.value[1]);
  let seriesData = Object.keys(mergeData).map((item, index) => {
    let arr = [];
    // const hasValue = mergeData[item].map(e => e.name.split(" ")[1]);
    for (let itemX of featData) {
      let found = false;
      for (let itemY of mergeData[item]) {
        if (itemX.value === itemY.name.split(" ")[1]) {
          itemX.num = itemY.value;
          found = true;
          break;
        }
      }
      if (!found) {
        itemX.num = null;
      }
    }
    arr = featData.map(ele => ele.num);
    return {
      name: item,
      type: "line",
      emphasis: {
        focus: "series",
        blurScope: "coordinateSystem"
      },
      symbol: "circle", // 设置有数据的点显示为圆形标记
      symbolSize: 8,
      itemStyle: {
        borderWidth: 2 // 可以设置标记的边框粗细
      },
      showSymbol: true, // 显示标记
      lineStyle: {
        type: "dashed" // 可以设置没有数据连接时的线条样式为虚线
      },
      yAxisIndex: index,
      // itemStyle: {
      //   color: "#4786FF"
      // },
      data: arr
    };
  });
  let xData = featData.map(item => item.value);
  let yAxisData = legendData.map((item, index) => {
    return {
      type: "value",
      name: `℃-Y${index + 1}`,
      offset: (0 + index) * 50,
      alignTicks: true,
      splitNumber: 5,
      axisLine: {
        lineStyle: {
          width: 2
        }
      }
    };
  });
  // optionData.value = { legendData, xData, yAxisData, seriesData };
  console.log(xData, mergeData, legendData, yAxisData, seriesData, "55555555555555555");
  alarmOptions.value = {
    title: {
      text: "点位报警历史曲线",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "24px",
      top: "15%",
      right: `${yAxisData.length * 30}`,
      bottom: "5%",
      containLabel: true
    },
    xAxis: {
      // type: "category",
      data: xData
    },
    yAxis: yAxisData,
    series: seriesData
  };
};

onMounted(async () => {
  // 获取区域列表
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  const id = JSON.parse(codes.filter(item => item.itemValue === "CR_POSITION_CODE")[0].itemDesc)[0].facCode; // 暂时写死一期厂区
  const data: any = await getFabZone();
  areaData.value = data;
  filterList.value = await queryDictData({ typeCode: "ALARM_LEVEL" });
  queryAllAlarm(null);
});
</script>

<template>
  <div class="details_box">
    <div class="top_turnback">
      <px-button type="primary" :icon="ArrowLeft" @click="turnBack">返回</px-button>
    </div>
    <div class="alarm_detail">
      <px-form ref="queryAlarmRef" class="custom-form-ui-new" :model="queryAlarmParams" :inline="true" label-width="68px">
        <px-form-item label="名称" prop="point" style="width: 220px">
          <!-- <px-select v-model="queryAlarmParams.point" clearable filterable placeholder="请选择名称">
            <px-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select> -->
          <px-input v-model="queryAlarmParams.point" clearable placeholder="请输入名称" />
        </px-form-item>
        <px-form-item label="级别" prop="alarmLevel" style="width: 220px">
          <px-select v-model="queryAlarmParams.alarmLevel" clearable filterable placeholder="请选择级别">
            <px-option v-for="item in filterList" :key="item.id" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="区域" prop="areaId" style="width: 220px">
          <px-select v-model="searchIdAlarm" placeholder="请选择区域" filterable @change="handleAreaChange">
            <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
          </px-select>
        </px-form-item>
        <!-- <px-form-item label="房间" prop="areaId" style="width: 220px">
        <px-select v-model="queryAlarmParams.roomId" clearable filterable placeholder="请选择房间">
          <px-option v-for="item in areaData" :key="item.value" :label="item.name" :value="item.code" />
        </px-select>
      </px-form-item> -->
        <px-form-item label="时间日期" style="width: 460px">
          <px-date-picker
            v-model="dateRangeAlarm"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </px-form-item>
        <px-form-item label="周期" prop="lifecycle" style="width: 220px">
          <px-select v-model="queryAlarmParams.lifecycle" clearable filterable placeholder="请选择周期" @change="handleChangeAlarm">
            <px-option v-for="item in testCompanyList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item>
          <px-button type="primary" @click="queryAllAlarm(null)">查询</px-button>
          <px-button @click="resetAlarmTable">重置</px-button>
        </px-form-item>
      </px-form>
      <px-row :gutter="24">
        <px-col :span="16">
          <barTitle title="Alarm列表" />
          <px-table
            ref="tableRef"
            v-loading="loading"
            max-height="389"
            :header-cell-style="{ background: '#e7eefb', color: '#000' }"
            border
            :data="tableAlarmData"
            show-overflow-tooltip
            :row-key="row => row.id"
            @selection-change="handleSelectionChange"
          >
            <px-table-column type="selection" width="40" :reserve-selection="true" />
            <px-table-column label="时间" align="center" prop="alarmTime" width="160" />
            <!-- <px-table-column label="组" align="center" prop="factoryId" /> -->
            <px-table-column label="名称" align="center" prop="point" />
            <px-table-column label="报警信息" align="center" prop="alarmContent" show-overflow-tooltip width="100" />
            <px-table-column label="级别" align="center" prop="alarmLevel" />
            <px-table-column label="当前值" align="center" prop="realityValue" />
            <!-- <px-table-column label="报警限" align="center" prop="settingValue" /> -->
            <px-table-column label="状态" align="center" prop="alarmStatus" />
            <!-- <px-table-column label="报警持续时间" align="center" prop="alarmDurationTime" width="180" /> -->
            <!-- <px-table-column label="未确认持续时间" align="center" prop="updateTime" width="160" /> -->
          </px-table>

          <pagination
            v-show="tableAlarmDataAll && tableAlarmDataAll.length > 0"
            v-model:page="queryAlarmParams.pageNum"
            v-model:limit="queryAlarmParams.pageSize"
            :total="tableAlarmDataAll.length"
            @pagination="queryAlarmTable"
          />
        </px-col>
        <px-col :span="8">
          <barTitle title="已选" />
          <px-table
            v-loading="loading"
            max-height="444"
            :header-cell-style="{ background: '#e7eefb', color: '#000' }"
            border
            :data="tableAlarmSelectedData"
            show-overflow-tooltip
          >
            <px-table-column label="时间" align="center" prop="alarmTime" width="160" />
            <!-- <px-table-column label="组" align="center" prop="factoryId" /> -->
            <px-table-column label="名称" align="center" prop="point" />
            <px-table-column label="报警信息" align="center" prop="alarmContent" show-overflow-tooltip width="100" />
            <px-table-column label="级别" align="center" prop="alarmLevel" />
            <px-table-column label="当前值" align="center" prop="realityValue" />
            <!-- <px-table-column label="报警限" align="center" prop="settingValue" /> -->
            <px-table-column label="状态" align="center" prop="alarmStatus" />
            <!-- <px-table-column label="报警持续时间" align="center" prop="alarmDurationTime" width="180" /> -->
            <!-- <px-table-column label="未确认持续时间" align="center" prop="updateTime" width="160" /> -->
          </px-table>
        </px-col>
      </px-row>
      <div class="con_spc">
        <div class="left_form">
          <barTitle title="曲线设置" />
          <div class="left_text">曲线开始时间</div>
          <px-date-picker v-model="lineBegin" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择日期与时间" />
          <div class="left_text">曲线宽度</div>
          <px-select v-model="lineWidth" clearable filterable placeholder="请选择曲线宽度" @change="handleChangeLine">
            <px-option v-for="item in minitesList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
          <div class="left_btn">
            <px-button type="primary" plain @click="queryAllAlarm('flag')">刷新曲线</px-button>
            <px-button style="width: 88px" plain @click="resetAlarm">重置</px-button>
          </div>
        </div>
        <div class="spc_com">
          <lineChart ref="spcChartRefDom" :key="new Date().getTime()" :width="800" :options="alarmOptions" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.details_box {
  box-sizing: border-box;
  width: 100%;
  min-height: 1300px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;

  .alarm_detail {
    width: 100%;
    min-width: 1300px;

    .con_spc {
      display: flex;
      justify-content: space-between;
      margin-top: 16px;

      .spc_com {
        // position: relative;
        flex: 1;

        .edit_form {
          display: flex;
          flex-flow: row nowrap;
          gap: 10px;
        }

        // .edit_y1 {
        //   position: absolute;
        //   cursor: pointer;
        // }
      }

      .left_form {
        margin-right: 16px;

        .left_text {
          margin: 16px 0 8px;
          font-size: 14px;
          color: rgb(0 0 0 / 80%);
        }

        .left_btn {
          margin-top: 16px;
        }
      }
    }

    .custom-form-ui-new {
      margin-top: 16px;
      margin-bottom: 0;
    }
  }

  .spc_detail {
    width: 100%;
    min-width: 1300px;

    .con_spc {
      display: flex;
      justify-content: space-between;
      margin-top: 16px;

      .spc_com {
        // position: relative;
        flex: 1;

        .edit_form {
          display: flex;
          flex-flow: row nowrap;
          gap: 10px;
        }

        // .edit_y1 {
        //   position: absolute;
        //   cursor: pointer;
        // }
      }
    }

    .import-bottle-title {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      width: 100%;
      height: 40px;
      padding-left: 16px;
      margin: 16px 0;
      line-height: 1;
      color: #333;
      background-color: #fef5e6;
      border: 1px solid #f7b648;
      border-radius: 6px;

      .download {
        margin-left: 8px;
        color: #3b82f6;
        cursor: pointer;
      }
    }
  }
}
</style>
